package com.network.filter;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import com.network.cfg.Configuration;
import com.network.entity.User;
import com.network.service.IUserService;

@Component("UserFilter")
public class UserFilter implements Filter {
	
	private IUserService userService;

	public void destroy() {
		
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		User u = (User) request.getSession().getAttribute(Configuration.USER);
		if (u == null) {
			//用户没有登录  则 返回登录界面
			response.sendRedirect(request.getContextPath() + Configuration.LOGIN_PAGE_PATH);
		} else {
			User user = userService.getUserById(u.getUserName());
			if(user == null || 
				!user.getPassword().equals(u.getPassword()) ||
				!u.getRole().equals(Configuration.USER_FLAG))
			{
				// 用户已经被删除 、 用户密码已经被修改 或者 用户没有权限 则 返回登录界面
				response.sendRedirect(request.getContextPath() + Configuration.LOGIN_PAGE_PATH);
			}
			else
			{
				// 一切都没有问题 则继续访问
				chain.doFilter(request, response);
			}
		}
		
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		
	}
	
	public IUserService getUserService() {
		return userService;
	}

	@Resource(name="userServiceImpl")
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

}
